package com.hk.Mgr.web.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.commons.BeanAndXMLTurn;
import com.hk.commons.ConstantPayment;
import com.hk.commons.HqlFilter;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Card;
import com.hk.commons.entity.UserCard;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.pay.FM;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.product.PaymentFromYm;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.sys.MD5Crypter;
import com.hk.service.IFundNav;
import com.hk.service.IOrganization;
import com.hk.service.kyc.ICard;
import com.hk.service.kyc.IUserCard;
import com.hk.service.order.IFYBackPayRecord;
import com.hk.service.order.IOrderInfo;
import com.hk.service.order.IPayment;
import com.hk.service.order.IPaymentFromYm;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.ISysUser;

/**
 * 数据修复Controller
 * 
 * @author 华康
 *
 */
@Controller
public class DataRepairCtr {
	private Logger logger = LoggerFactory.getLogger(DataRepairCtr.class);
	@Autowired
	private IPaymentFromYm PaymentFromYmS;
	@Autowired
	private IPayment paymentService;
	@Autowired
	private ISysUser sysUserService;
	@Autowired
	private IOrderInfo orderInfoService;

	@Autowired
	private IUserCard userCardService;

	@Autowired
	private ICard cardService;

	@Autowired
	public IFundNav fundNavService;

	@Autowired
	private IProductInfo productService;

	@Autowired
	private IOrganization orgService;

	@Autowired
	private IFYBackPayRecord fyService;

	@Value("${fy.Secret}")
	private String fySecret;

	@Value("${fy.mchntCd}")
	private String fyMchntCd;

	@Value("${fy.scheme}")
	private String scheme;

	@Value("${fy.valiFour}")
	private String realUrl;

	@Value("${fy.validateCardPath}")
	private String path;

	@Value("${fy.getBankPath}")
	private String getBankpath;

	@RequestMapping(value = "/testSlowQuery", method = RequestMethod.GET)
	@ResponseBody
	public void testSlowQuery() {
		SysUser user=new SysUser();
		Long id=sysUserService.add(user);
		System.out.println(id);
//		OrderInfo orderInfo = orderInfoService.findById(84383771745580L);
//		UserCard userCard = userCardService.findById(orderInfo.getUserCardId());
//		int cardId = userCard.getCardId();
//		BigDecimal amount = orderInfo.getSuccessAmount();
//		ProductInfo productInfo = productService.findById(orderInfo
//				.getProductId());
//		System.out.println(getExtraProfit(cardId, amount,
//				productInfo.getProTerm()));
	}

	private BigDecimal getExtraProfit(int cardId, BigDecimal amount, int days) {
		BigDecimal extraProfit = new BigDecimal(0);
		Card card = cardService.findById(cardId);
		BigDecimal rate = card.getRate();
		extraProfit = amount.multiply(rate).multiply(new BigDecimal(days))
				.divide(new BigDecimal(365), 5, BigDecimal.ROUND_HALF_UP);
		// 使用加息券后单笔额外增加的利润最高为5000元，超过5000元仍按5000元发放；
		if (extraProfit.compareTo(new BigDecimal(5000)) == 1) {// 1是大于
			extraProfit = new BigDecimal(5000);
		}
		return extraProfit;
	}

	@RequestMapping(value = "/updateOrderInfo", method = RequestMethod.GET)
	@ResponseBody
	public void updateOrderInfo() {// 订单表区分客户产品收益和加息收益 ，更新相关信息
		/*
		 * private BigDecimal extraDividend; private BigDecimal prodDividend;
		 * private Long userCardId; private String channelName; private Integer
		 * orgId;
		 */
		BigDecimal extraDividend = new BigDecimal(0);
		HqlFilter cardFilter = new HqlFilter();
		cardFilter.addEQFilter("status", 1);// 已使用的加息券
		List<UserCard> userCardList = userCardService.findByFilter(cardFilter);

		if (userCardList.size() > 0) {
			for (UserCard userCard : userCardList) {
				Long orderId = userCard.getOrderId();
				OrderInfo cardOrderInfo = orderInfoService.findById(orderId);
				if (cardOrderInfo != null) {
					ProductInfo productInfo = productService
							.findById(cardOrderInfo.getProductId());
					extraDividend = getExtraProfit(userCard.getCardId(),
							cardOrderInfo.getSuccessAmount(),
							productInfo.getProTerm());
					cardOrderInfo.setExtraDividend(extraDividend);
					cardOrderInfo.setUserCardId(userCard.getId());
					orderInfoService.update(cardOrderInfo);
				}
			}
		}

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("payStatus", 2);
		List<OrderInfo> orderList = orderInfoService.findByFilter(hqlFilter);
		if (orderList.size() > 0) {
			for (OrderInfo orderInfo : orderList) {
				/*-------------------------设置产品收益------------------------*/
				ProductInfo productInfo = productService.findById(orderInfo
						.getProductId());
				BigDecimal prodDividend = new BigDecimal(0);

				if (productInfo != null) {
					BigDecimal yearRate = new BigDecimal(productInfo
							.getMaxYearRate().replace("%", ""))
							.divide(new BigDecimal(100));
					int days = productInfo.getProTerm();
					// 投资金额*年化收益率*30/360*(投资天数/30)
					prodDividend = orderInfo
							.getSuccessAmount()
							.multiply(yearRate)
							.multiply(new BigDecimal(days))
							.divide(new BigDecimal(365), 5,
									BigDecimal.ROUND_HALF_UP);
					orderInfo.setProdDividend(prodDividend);
				}

				/*-------------------------设置渠道名称和机构id------------------------*/
				orderInfo.setChannelName("无主客户");
				Long financialPlannerId = orderInfo.getFinancialPlannerId();
				if (financialPlannerId != null) {
					orderInfo.setFinancialPlannerId(financialPlannerId);
					SysUser finalcialUser = sysUserService
							.findById(financialPlannerId);
					if (finalcialUser != null) {
						if (finalcialUser.getOrgId() != null) {
							int orgId = finalcialUser.getOrgId();
							orderInfo.setOrgId(orgId);
							orderInfo.setChannelName(orgService
									.getChannelName(orgId));
						}
					}
				}

				orderInfoService.update(orderInfo);
				System.out.println("产品收益：" + orderInfo.getProdDividend()
						+ "-加息收益" + orderInfo.getExtraDividend() + "-加息券id"
						+ orderInfo.getUserCardId() + "-机构id"
						+ orderInfo.getOrgId() + "-渠道名称"
						+ orderInfo.getChannelName());
			}
		}
		System.out.print("OK");
	}

	/**
	 * 更新收益
	 */
	@RequestMapping(value = "/updateHkDividend", method = RequestMethod.GET)
	@ResponseBody
	public void updateHkDividend() {
		HqlFilter filter = new HqlFilter();
		filter.addEQFilter("companyId", 1);
		// filter.addEQFilter("id", 82342579076927L);
		List<OrderInfo> orderList = orderInfoService.findByFilter(filter);
		for (OrderInfo orderInfo : orderList) {
			if (orderInfo.getPayStatus() == 2) {// 已支付
				BigDecimal amount = orderInfo.getSuccessAmount();
				BigDecimal dividend = new BigDecimal("0");
				Long productId = orderInfo.getProductId();
				ProductInfo productInfo = productService.findById(productId);
				if (productInfo != null) {
					BigDecimal yearRate = new BigDecimal(productInfo
							.getMaxYearRate().replace("%", ""))
							.divide(new BigDecimal(100));
					int days = productInfo.getProTerm();
					dividend = amount
							.multiply(yearRate)
							.multiply(new BigDecimal(days))
							.divide(new BigDecimal(365), 4,
									BigDecimal.ROUND_HALF_UP);
					/*
					 * 可以通过BigDecimal的compareTo方法来进行比较.
					 * 返回的结果是int类型,-1表示小于,0是等于,1是大于.
					 */
					if (dividend.compareTo(orderInfo.getDividend()) == 0) {
						System.out.println("订单id:" + orderInfo.getId() + "原收益："
								+ orderInfo.getDividend());
						orderInfo.setDividend(dividend);
						orderInfoService.update(orderInfo);
						System.out.println("订单id:" + orderInfo.getId() + "现收益："
								+ orderInfo.getDividend());
					}

				}

			}
		}
	}

	@RequestMapping(value = "/updateDividend", method = RequestMethod.GET)
	@ResponseBody
	public void updateDividend() {
		HqlFilter filter = new HqlFilter();
		filter.addEQFilter("companyId", 1);
		// filter.addEQFilter("userId", 70749128744208L);
		List<OrderInfo> orderList = orderInfoService.findByFilter(filter);
		for (OrderInfo orderInfo : orderList) {
			if (orderInfo.getPayStatus() != 0) {
				BigDecimal amount = orderInfo.getSuccessAmount();
				Long productId = orderInfo.getProductId();
				ProductInfo productInfo = productService.findById(productId);
				if (productInfo != null) {
					BigDecimal yearRate = new BigDecimal(productInfo
							.getMaxYearRate().replace("%", ""))
							.divide(new BigDecimal(100));
					int days = productInfo.getProTerm();
					// 投资金额*年化收益率*30/365*(投资天数/30)
					if (orderInfo.getDividend() == null) {
						BigDecimal dividend = new BigDecimal(0);
						dividend = amount.multiply(yearRate)
								.divide(new BigDecimal(365), 4)
								.multiply(new BigDecimal(days))
								.setScale(2, BigDecimal.ROUND_HALF_UP);
						orderInfo.setDividend(dividend);
					}
					if (orderInfo.getOrderTradeDate() == null) {
						Long orderCreateOn = orderInfo.getOrderCreatedOn();
						Calendar nowCalendar = Calendar.getInstance();
						nowCalendar.setTime(new Date(orderCreateOn));
						System.out.println("创建时间："
								+ nowCalendar.get(Calendar.YEAR)
								+ nowCalendar.get(Calendar.MONTH)
								+ nowCalendar.get(Calendar.DAY_OF_MONTH));
						nowCalendar.add(Calendar.DAY_OF_MONTH, +1);// +1今天的时间加一天
						Calendar calendar = Calendar.getInstance();
						calendar.set(nowCalendar.get(Calendar.YEAR),
								nowCalendar.get(Calendar.MONTH),
								nowCalendar.get(Calendar.DAY_OF_MONTH), 0, 0, 1);
						Long orderTradeDate = calendar.getTime().getTime();
						calendar.add(Calendar.DAY_OF_YEAR, days);
						System.out.println("还本付息时间："
								+ calendar.get(Calendar.YEAR)
								+ calendar.get(Calendar.MONTH)
								+ calendar.get(Calendar.DAY_OF_MONTH));
						Long orderDividendDate = calendar.getTime().getTime();
						orderInfo.setOrderConfirmDate(orderTradeDate);
						orderInfo.setOrderTradeDate(orderTradeDate);
						orderInfo.setDividendDate(orderDividendDate);
					}
					orderInfoService.update(orderInfo);
					System.out.println("更新收益");
				}
			}

		}
		System.out.println("OK");
	}

	@RequestMapping(value = "/updateUserId", method = RequestMethod.GET)
	@ResponseBody
	public void updateUserId() {
		HqlFilter hqlFilter = new HqlFilter();
		List<Payment> list = paymentService.findByFilter(hqlFilter);
		for (Payment payment : list) {
			if (payment.getUserId() == null) {
				String phone = payment.getPhone();
				if (!StringHelper.isEmpty(phone)) {
					HqlFilter sysFilter = new HqlFilter();
					sysFilter.addEQFilter("Name", phone);
					List<SysUser> userList = sysUserService
							.findByFilter(sysFilter);
					if (userList.size() > 0) {
						if (userList.size() == 1) {
							payment.setUserId(userList.get(0).getId());
							System.out.println("执行更新，手机号为" + phone);
							paymentService.update(payment);

						} else {
							System.out
									.println("该手机有多条user记录，不能更新！手机号为" + phone);
						}
					}
				}

			}

		}

	}

	// @RequestMapping(value = "/testFilter", method = RequestMethod.GET)
	// @ResponseBody
	// public void testFilter() {
	// StringBuffer buf = new StringBuffer();
	// String hql2 =
	// "Select new com.hk.commons.vo.TestOrderProduct(i.brokerOrderNo,i.successAmount,p.name) from OrderInfo i,ProductInfo p where i.productId=p.id and p.id=79340374748599";
	// // List<TestOrderProduct> list = orderInfoService.executeListHql(hql2,
	// // 0,
	// // 10);
	// List<TestOrderProduct> list = orderInfoService.executeListHql(hql2);
	// for (TestOrderProduct o : list) {
	// System.out.println(new JSONObject(o));
	// }
	//
	// System.out.println("OK");
	// }

	// @RequestMapping(value = "/ttttexcel")
	// @ResponseBody
	// public void excelExport(HttpServletRequest request,
	// HttpServletResponse response) {
	// // 缺一条数据
	//
	// StringBuffer buf = new StringBuffer();
	// // select
	// //
	// p.accountName,p.phone,p.bankName,p.paymentNo,fb.amt,fb.orderDate,pro.name
	// // from t_pay_fyBackRecord fb,t_payment p,t_order_info o,t_product_info
	// // pro where pro.id=o.productId and p.id=o.paymentId and
	// // o.id=fb.mchntOrderId and fb.responseCode='0000'
	//
	// String hql2 =
	// "Select new com.hk.commons.vo.FYExcelBean(p.accountName,p.phone,p.bankName,p.paymentNo,fb.amt,fb.orderDate,pro.name) "
	// + "from FYBackPayRecord fb,Payment p,OrderInfo o,ProductInfo pro where "
	// +
	// "pro.id=o.productId  and p.id=o.paymentId and o.id=fb.mchntOrderId and fb.responseCode='0000'";
	// List<FYExcelBean> fyList = orderInfoService.executeListHql(hql2);
	//
	// String head = "用户姓名、手机号、银行开户行、银行卡号、订单金额、交易时间、产品名称";
	// ExcelHelper newExcel = new ExcelHelper(fyList, head);
	// HSSFWorkbook wb = newExcel.outputExcel();
	// response.setContentType("application/vnd.ms-excel");
	// String titlename = "富友测试订单明细";
	// try {
	// response.setHeader("Content-disposition", "attachment; filename="
	// + new String((titlename).getBytes("gbk"), "iso8859-1")
	// + ".xls");
	// } catch (UnsupportedEncodingException e1) {
	// // TODO Auto-generated catch block
	// e1.printStackTrace();
	// }
	//
	// OutputStream ouputStream;
	// try {
	// ouputStream = response.getOutputStream();
	// wb.write(ouputStream);
	// ouputStream.flush();
	// ouputStream.close();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }

	@RequestMapping(value = "/handleBankInfo", method = RequestMethod.GET)
	@ResponseBody
	public void handleBankInfo() {
		HqlFilter hqlFilter = new HqlFilter();
		List<Payment> allPayments = paymentService.findByFilter(hqlFilter);
		for (Payment payment : allPayments) {
			if (StringHelper.isEmpty(payment.getCardType())) {
				String paymentNo = payment.getPaymentNo();
				// String bankName = payment.getBankName();
				// if (StringHelper.isEmpty(bankName)) {
				FM fm = getBankInfo(paymentNo);
				if (fm != null) {
					payment.setBankName(fm.getCnm());
					payment.setInsCard(fm.getInscd());
					payment.setCardType(fm.getCtp());

					paymentService.update(payment);
				}
				// }
			}

		}
		System.out.println("OK");
	}

	private FM getBankInfo(String cardNum) {
		URIBuilder builder = new URIBuilder().setScheme(scheme)
				.setHost(realUrl).setPath(getBankpath);
		Map<String, String> trimmedParams = new HashMap<>();
		String MchntCd = fyMchntCd;
		String Ono = cardNum;
		String allUrl = MchntCd + "|" + Ono + "|" + fySecret;
		String Sign = MD5Crypter.md5Encrypt(allUrl);
		String fm = "<FM><MchntCd>" + MchntCd + "</MchntCd>" + "<Ono>" + Ono
				+ "</Ono>" + "<Sign>" + Sign + "</Sign></FM> ";
		trimmedParams.put("FM", fm);
		CloseableHttpResponse resp = null;
		CloseableHttpClient httpClient = null;
		try {
			URI uri = builder.build();
			RequestBuilder requestBuilder = RequestBuilder.post(uri);
			List<NameValuePair> kvs = new ArrayList<>();
			for (String key : trimmedParams.keySet()) {
				kvs.add(new BasicNameValuePair(key, trimmedParams.get(key)));
			}
			requestBuilder.setEntity(new UrlEncodedFormEntity(kvs, "UTF-8"));
			HttpUriRequest request = requestBuilder.build();

			httpClient = HttpClients.custom().setMaxConnPerRoute(200).build();

			resp = httpClient.execute(request);

			if (resp.getStatusLine().getStatusCode() >= 300) {
				System.err.println("Something wrong: "
						+ resp.getStatusLine().toString());
			}
			BufferedReader input = new BufferedReader(new InputStreamReader(
					resp.getEntity().getContent(), "UTF-8"));
			StringBuilder sb = new StringBuilder();
			char[] buf = new char[1000];
			int count;
			while ((count = input.read(buf)) > 0) {
				sb.append(buf, 0, count);
			}
			logger.info("查询该银行卡号信息如下：Ono={},sb={}", Ono, sb.toString());
			// System.out.println(sb.toString());
			String result = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
					+ sb.toString().toLowerCase();
			BeanAndXMLTurn<FM> ff = new BeanAndXMLTurn<FM>();
			FM fmresultFm = ff.XMLStringToBean(result, new FM());

			return fmresultFm;
		} catch (IOException | URISyntaxException e) {
			logger.error("fyValidate()方法异常！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (resp != null) {
					resp.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				logger.error("获取卡信息异常");
				e.printStackTrace();

			}
		}
	}

	@RequestMapping(value = "/testadd", method = RequestMethod.GET)
	@ResponseBody
	public void testadd() {

		Payment payment = new Payment();
		payment.setAccountName("11111");
		payment.setIdentityNo("11111");

		payment.setPaymentNo("11111");
		payment.setPhone("11111");
		//payment.setCardStatus(ConstantPayment.FYJZH_PAY);
		paymentService.add(payment);
	}

	// @RequestMapping(value = "/importExcel", method = RequestMethod.GET)
	// // 导入excel
	// @ResponseBody
	// public void importExcel() {
	// int i;
	// Sheet sheet;
	// Workbook book;
	// Cell cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8;
	// String phone, name, paymentMethodId, paymentNo, accountName, identityNo,
	// accountId;
	// try {
	// // t.xls为要读取的excel文件名
	// File file = new File("D:\\t2.xls");
	// book = Workbook.getWorkbook(file);
	//
	// // 获得第一个工作表对象(ecxel中sheet的编号从0开始,0,1,2,3,....)
	// sheet = book.getSheet(0);
	// // 获取左上角的单元格
	// cell1 = sheet.getCell(0, 0);
	// System.out.println("标题：" + cell1.getContents());
	//
	// i = 1;
	// while (true) {
	// // 获取每一行的单元格
	// PaymentFromYm test03 = new PaymentFromYm();
	// phone = sheet.getCell(0, i).getContents();// （列，行）
	// accountId = sheet.getCell(1, i).getContents();
	// accountName = sheet.getCell(2, i).getContents();
	// identityNo = sheet.getCell(4, i).getContents();// （列，行）
	// paymentNo = sheet.getCell(5, i).getContents();
	// name = sheet.getCell(6, i).getContents();
	// paymentMethodId = sheet.getCell(7, i).getContents();
	// test03.setPhone(phone);
	// test03.setAccountId(accountId);
	// test03.setAccountName(accountName);
	// test03.setIdentityNo(identityNo);
	// test03.setPaymentNo(paymentNo);
	// test03.setName(name);
	// test03.setPaymentMethodId(paymentMethodId);
	// PaymentFromYmS.add(test03);
	// if ("".equals(cell1.getContents()) == true) // 如果读取的数据为空
	// break;
	// System.out.println(phone + "\t" + accountId + "\t"
	// + accountName + "\t" + identityNo + "\t" + paymentNo
	// + "\t" + name + "\t" + paymentMethodId);
	// i++;
	// }
	// book.close();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	//
	// @RequestMapping(value = "/importUserExcel", method = RequestMethod.GET)
	// // 导入excel
	// @ResponseBody
	// public void importUserExcel() {
	// int i;
	// Sheet sheet;
	// Workbook book;
	// Cell cell1, cell2, cell3, cell4;
	// String company, fianlName, custName, custPhone;
	// try {
	// // t.xls为要读取的excel文件名
	// File file = new File("D:\\t2.xls");
	// book = Workbook.getWorkbook(file);
	//
	// // 获得第一个工作表对象(ecxel中sheet的编号从0开始,0,1,2,3,....)
	// sheet = book.getSheet(0);
	// // 获取左上角的单元格
	// cell1 = sheet.getCell(0, 0);
	// System.out.println("标题：" + cell1.getContents());
	//
	// i = 1;
	// while (i < 59) {
	// // 获取每一行的单元格
	//
	// company = sheet.getCell(0, i).getContents();// （列，行）
	// fianlName = sheet.getCell(1, i).getContents();
	// custName = sheet.getCell(2, i).getContents();
	// custPhone = sheet.getCell(3, i).getContents();// （列，行）
	// if ("".equals(cell1.getContents()) == true) // 如果读取的数据为空
	// break;
	// System.out.println(company + "\t" + fianlName + "\t" + custName
	// + "\t" + custPhone);
	//
	// HqlFilter filter = new HqlFilter();
	// filter.addEQFilter("Name", custPhone);
	// List<SysUser> sysList = sysUser.findByFilter(filter);
	// SysUser custUser = new SysUser();
	// if (sysList.size() > 0) {
	// custUser = sysList.get(0);
	// if (StringHelper.isEmpty(custUser.getRealName())) {
	// custUser.setRealName(custName);
	// }
	// sysUser.update(custUser);
	// }
	//
	// i++;
	// // test03.setPhone(phone);
	// // test03.setAccountId(accountId);
	// // test03.setAccountName(accountName);
	// // test03.setIdentityNo(identityNo);
	// // test03.setPaymentNo(paymentNo);
	// // test03.setName(name);
	// // test03.setPaymentMethodId(paymentMethodId);
	// // PaymentFromYmS.add(test03);
	//
	// }
	// book.close();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }

	@RequestMapping(value = "/addUserNametoSysUser", method = RequestMethod.GET)
	@ResponseBody
	public void addUserNametoSysUser(@RequestParam String phone) {
		HqlFilter filter = new HqlFilter();
		List<Payment> paymentList = paymentService.findByFilter(filter);
		for (Payment payment : paymentList) {
			String accountName = payment.getAccountName();
			if (StringHelper.isNotEmpty(accountName)) {
				Long userId = payment.getUserId();
				SysUser user = sysUserService.findById(userId);
				if (user != null) {
					String realName = user.getRealName();
					if (StringHelper.isEmpty(realName)) {
						user.setRealName(accountName);
						sysUserService.update(user);
						System.out.println("更新用户名：" + accountName);
					}
				}
			}

		}

		System.out.println("OK");

	}

	@RequestMapping(value = "/tttt", method = RequestMethod.GET)
	@ResponseBody
	public void tt(@RequestParam String phone) {// 把盈米的

		// 1.hkServer.t_payment 有paymentNo 且 test.t_pay_03 也有， 则依据 test.t_pay_03
		// 将 hkServer.t_payment 表中的数据补齐。

		// 2.hkServer.t_payment 没有paymentNo 且 test.t_pay_03 有， 则将 test.t_pay_03
		// 中数据加入 hkServer.t_payment 表中。

		// accountname,identity,paymentno,paymentme
		HqlFilter hqlFilter03 = new HqlFilter();
		List<PaymentFromYm> payment03List = PaymentFromYmS
				.findByFilter(hqlFilter03);
		for (PaymentFromYm p03 : payment03List) {
			String paymentNo = p03.getPaymentNo();
			if (StringHelper.isNotEmpty(paymentNo)) {
				HqlFilter pamentFilter = new HqlFilter();
				pamentFilter.addEQFilter("paymentNo", paymentNo);
				List<Payment> pamentList = paymentService
						.findByFilter(pamentFilter);
				if (pamentList.size() > 0) {// 有就补齐
					System.out.println("共有" + pamentList.size()
							+ "条数据，paymentNo=" + paymentNo);
					for (Payment payment : pamentList) {
						boolean ifUpdate = false;
						String accoutName = payment.getAccountName();
						String identityNo = payment.getIdentityNo();
						String paymentMethodId = payment.getPaymentMethodId();
						if (StringHelper.isEmpty(accoutName)) {
							ifUpdate = true;
							payment.setAccountName(p03.getAccountName());
						}
						if (StringHelper.isEmpty(identityNo)) {
							ifUpdate = true;
							payment.setIdentityNo(p03.getIdentityNo());
						}
						if (StringHelper.isEmpty(paymentMethodId)) {
							ifUpdate = true;
							payment.setPaymentMethodId(p03.getPaymentMethodId());
						}
						if (ifUpdate) {
							System.out.println("执行更新");
							paymentService.update(payment);
						}
					}
				} else {// 加入记录
					Payment newPayment = new Payment();
					newPayment.setAccountName(p03.getAccountName());
					newPayment.setBankId(p03.getBankId());
					newPayment.setCts(p03.getCts());
					newPayment.setLastUseTime(p03.getLastUseTime());
					newPayment.setIdentityNo(p03.getIdentityNo());
					newPayment.setPaymentMethodId(p03.getPaymentMethodId());
					newPayment.setPaymentNo(p03.getPaymentNo());
					newPayment.setPhone(p03.getPhone());
					newPayment.setSupportCompany(p03.getSupportCompany());
					newPayment.setUserId(p03.getUserId());
					newPayment.setCardStatus(1);
					paymentService.add(newPayment);
				}
			}

		}
		System.out.println("aa");
	}
}
